﻿using System.Web.Mvc;

namespace CollectionBindingExample
{
	public class ScheduleBinder : DefaultModelBinder
	{
		protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor)
		{
			base.BindProperty(controllerContext, bindingContext, propertyDescriptor);

			if (!string.Equals(propertyDescriptor.Name, "Duration") || bindingContext.ModelState.ContainsKey("Duration"))
				return;
			
			var hoursValue= bindingContext.ValueProvider.GetValue("hours");
			var minutesValue = bindingContext.ValueProvider.GetValue("minutes");

			int hours = 0;
			int minutes = 0;

			if (hoursValue == null || minutesValue == null ||
				!int.TryParse(hoursValue.AttemptedValue, out hours) || !int.TryParse(minutesValue.AttemptedValue, out minutes))
			{
				hours = 3;
			}
						
			propertyDescriptor.SetValue(bindingContext.Model, (hours * 60 + minutes));
		}
	}
}